<?php


$this->AddHook('neighbor_list', 'GetNeighborList');

//CREATE AND UPDATE NEIGHBORS LIST BY TONYCELL=====================
function GetNeighborList($bot)
{
	$imagePath = substr($_SERVER["PHP_SELF"], 0, strpos($_SERVER["PHP_SELF"], "/"));
	$XMLconfigFile = $imagePath . "Profiles\\" . $bot->zySnuid . '__Zy.xml';
	$XMLconfig = new Zend_Config_Xml($XMLconfigFile);

	//****************************************************************
	$bot->SendMsg('# -------------------------------');
	$bot->SendMsg('# Getting NeighborList Phase #1');
	$bot->ld->ExecQuery("drop table if exists 'neighborlist'");
	$bot->ld->ExecQuery("CREATE TABLE [neighborlist] ([uid] NVARCHAR(25) NULL,[name] NVARCHAR(50) NULL, [picture] NVARCHAR(80) NULL,[cityname] NVARCHAR(50) NULL,[xp] NVARCHAR(10)  NULL,[coins] NVARCHAR(20)  NULL, [level] INTEGER) ");

	$dneighbors = array();
	$dneighbors = $bot->cfg->_value['data'][1]['data']['neighbors'];

	if(is_array($dneighbors))
	{
		foreach($dneighbors as $key=>$val)
		{
			if(is_array($val))
			{
				//[uid] NVARCHAR(25) NULL,
				//[name] NVARCHAR(50) NULL,
				//[picture] NVARCHAR(50) NULL,
				//[cityname] NVARCHAR(50) NULL,
				//[xp] NVARCHAR(10) NULL,
				//[coins] NVARCHAR(20) NULL,
				//[level] NVARCHAR(5)  NULL)

				$EQ = 'INSERT INTO neighborlist VALUES (';
				$EQ .= '"' . $val['uid'] . '",';
				$EQ .= '"", "",';//name & picture - to get later on 2nd phase
				$EQ .= '"' . $val['cityname'] . '",';
				$EQ .= '"' . $val['xp'] . '",';
				$EQ .= '"' . $val['gold'] . '",';
				$EQ .= '"' . (int)$val['level'] . '")';
				//$bot->SendMsg($EQ);
				$bot->ld->ExecQuery($EQ);
			}
		}
	}

	//http://fb-0.cityville.zynga.com/flash.php?
	//isOuterIframe=1
	//&zySnid=1
	//&zyAuthHash=ed1d2dbacb8233ec3e4765c88436c9f1
	//&zySig=c0e97d144ad0ec354cf295f416d54cbd
	//&zySnid=1
	//&zyAuthHash=ed1d2dbacb8233ec3e4765c88436c9f1
	//&zySig=c0e97d144ad0ec354cf295f416d54cbd

	$bot->SendMsg('# Getting NeighborList Phase #2');
	$url = 'http://fb-0.cityville.zynga.com/flash.php?';
	//$url = 'http://'.$bot->host.'/flash.php?';
	$url .= 'isOuterIframe=1';
	$url .= '&zySnid=1';
	$url .= '&zyAuthHash=' . $XMLconfig->zyAuthHash;
	$url .= '&zySig=' . $XMLconfig->zySig;

	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_HEADER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_REFERER, "http://apps.facebook.com/cityville/flash.php");
	//curl_setopt($ch, CURLOPT_PROXY, "localhost:8888" );
	curl_setopt($ch, CURLOPT_USERAGENT, $XMLconfig->UserAgent);
	curl_setopt($ch, CURLOPT_COOKIE, $XMLconfig->Cookie);
	curl_setopt($ch, CURLOPT_POST, false);
	curl_setopt($ch, CURLOPT_HTTPGET, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$output = curl_exec($ch);
	curl_close($ch);

	$outputArray = explode("\n", $output);
	$found = 0;
	foreach($outputArray as $line)
	{
		if(strpos($line, 'g_friendData'))
		{
			$line = strstr($line, '[');
			$line = substr($line, 0, -1);
			if ($line==null) continue;
			//$line = substr($line, stripos($line,'g_friendData')+15);
			//var_dump(json_decode($line, true));
			$tmp = json_decode($line, true);

			foreach($tmp as $index=>$params)
			{
				//[uid] NVARCHAR(25) NULL,
				//[name] NVARCHAR(50) NULL,
				//[picture] NVARCHAR(50) NULL,
				//[cityname] NVARCHAR(50) NULL,
				//[xp] NVARCHAR(10) NULL,
				//[coins] NVARCHAR(20) NULL,
				//[level] NVARCHAR(5)  NULL)

				$EQ = 'UPDATE neighborlist SET ';
				$EQ .= 'name="' . $params['name'] . '",';
				$EQ .= 'picture="' . $params['pic_small'] . '" ';
				$EQ .= 'WHERE uid="' . $params['uid'] . '"';
				//$bot->SendMsg($EQ);
				$bot->ld->ExecQuery($EQ);
			}
		}
	}
	$bot->SendMsg('# Getting NeighborList done.');
	$bot->SendMsg('# -------------------------------');
	/*
//****************************************************************
$bot->SendMsg('# Getting NeighborList Phase #2');
$url = 'http://'. $bot->host . '/neighbors.php?';
$url .= '&zySnid=1'; //.   $this->XMLconfig->zySnid;    //zySnid=1&
$url .= '&zyAuthHash='. $XMLconfig->zyAuthHash;    //zyAuthHash=f1f1f1f1f1f1f1f1f1f1f1ff1f1&
$url .= '&zySig='.      $XMLconfig->zySig;         //zySig=44ff44dd44ee55ee55ee66ff77dd66ee

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_REFERER, "http://www.facebook.com/plugins/serverfbml.php");
//curl_setopt($ch, CURLOPT_PROXY, "localhost:8888" );
curl_setopt($ch, CURLOPT_USERAGENT, $XMLconfig->UserAgent);
curl_setopt($ch, CURLOPT_COOKIE, $XMLconfig->Cookie);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);

//$bot->SendMsg($output);
$outputArray = explode("\n", $output);
$found = 0;
foreach($outputArray as $line)
{
if (($found == 0) && (strpos($line, 'class="n_list_info">')))
{
//$bot->SendMsg('ACHOU');
//$bot->SendMsg("# " . trim(strip_tags($line)));
//echo date(DATE_RFC822) . ' ' .$line; //$found = 1;}
$found = 1;
}
else
if ($found == 1) //Name & uid
{
$iuid = substr($line, stripos($line,'visitId=')+8, 11);
if ($iuid == '><a href="h')
{
$found = 0;
}
else
{
$found = 2;
}
}
else
if ($found == 2) //level
{
$ilevel =  substr(strrchr($line, ":"), 1);
$ilevel = trim(strip_tags($ilevel));
$found = 3;
}
else
if ($found == 3) //xp
{
$ixp = substr(strrchr($line, ":"), 1);
$ixp = trim(strip_tags($ixp));
$found = 4;
}
else
if ($found == 4) //coins
{
//[uid] NVARCHAR(25) NULL,
//[name] NVARCHAR(50) NULL,
//[picture] NVARCHAR(50) NULL,
//[cityname] NVARCHAR(50) NULL,
//[xp] NVARCHAR(10) NULL,
//[coins] NVARCHAR(20) NULL,
//[level] NVARCHAR(5)  NULL)

$icoins =  substr(strrchr($line, ":"), 1);
$icoins = trim(strip_tags($icoins));
$EQ  = 'UPDATE neighborlist SET ';
$EQ .= 'xp="'.$ixp.'", ';
$EQ .= 'coins="'.$icoins.'", ';
$EQ .= 'level="'.$ilevel.'" ';
$EQ .= 'WHERE uid="'.$iuid.'"';
$bot->SendMsg($EQ);
$bot->ld->ExecQuery($EQ);
$found = 0;
}
}

*/
}
//LIST OF PENDING REQUESTS FOR FRANCHISES BY TONYCELL=====================
$this->AddHook('pending_franchises', 'GetPendingFRequest');
function GetPendingFRequest($bot)
{
	$orders = $bot->cfg->_value['data'][0]['data']['userInfo']['player']['Orders'];
	if(isset($orders))
	//foreach($orders as $order)
	{
		$lotsites = $orders['order_lot'];
		if(isset($lotsites))
		{
			$received = $lotsites['received'];
			if(isset($received))
			{
				$pending = $received['pending'];
				if(isset($pending) && is_array($pending))
				{
					$bot->ld->ExecQuery("drop table if exists 'fpending'");
					$bot->ld->ExecQuery("CREATE TABLE [fpending] ([lotId] NVARCHAR(6) NULL,[resourceType] NVARCHAR(50) NULL, [senderID] NVARCHAR(15) NULL)");
					//[lotId] NVARCHAR(6) NULL,
					//[resourceType] NVARCHAR(50) NULL,
					//[senderID] NVARCHAR(15) NULL

					foreach($pending as $key=>$val)
					{
						$EQ = 'INSERT INTO fpending VALUES (';
						$EQ .= '"' . $val['lotId'] . '",';
						$EQ .= '"' . $val['resourceType'] . '",';//mixed string, not only the classname
						$EQ .= '"' . $val['senderID'] . '")';
						//$bot->SendMsg($EQ);
						$bot->ld->ExecQuery($EQ);
					}
				}
			}
		}

	}
}
//ACCEPTING SELECTED FRANCHISES (06.09.2011) BY TONYCELL=====================
//$this->AddHook('accept_pending_franchises', 'AcceptPendingFRequest');
function AcceptPendingFRequest($bot, $data)
{
	//$data = $bot->ld->GetPlSettings("neighborsplugin");
	//if( ! isset($data->pause))
	//{
	//   $data->pause = 1;
	//   $bot->ld->SavePlSettings("neighborsplugin", $data);
	//}
	if( ! isset($data->flist) || (count($data->flist) == 0))
	return;

	$bot->SendMsg('=====================================');
	$bot->SendMsg('[Franchise-Accepting] Start accepting Franchises...');
	$bot->ReloadConfig();

	//print_r($data->flist);

	foreach($data->flist as $index=>$sosed)
	{
		//[lotId] NVARCHAR(6) NULL,
		//[resourceType] NVARCHAR(50) NULL,
		//[senderID] NVARCHAR(15) NULL

		$tmp = explode("|", $sosed);
		$lotId = trim($tmp[0]);
		$senderID = trim($tmp[2]);

		$N = array();

		//if ((int)$lotId == -1) continue; //Skip non-identifieds lotsites

		$bot->SendMsg('[NEIGHBORS-Franchise] Accepting: ' . $senderID . ' on LotSite:' . $lotId);

		$accept = 0;
		$err = "";
		//looking for the lot number
		if(is_array($bot->cfg->_value['data'][0]['data']['userInfo']['world']['objects']))
		{
			foreach($bot->cfg->_value['data'][0]['data']['userInfo']['world']['objects'] as $obj)
			{
				$found = 0;
				if($obj['className'] == "LotSite")
				{
					$found++;
					if($lotId == 1) //add Franchise in any lot
					{
						$N['lotId'] = (int)$obj['id'];
						$N['senderID'] = (string)$senderID;

						$bot->AcceptFranchiseRequest($N);
						$err = $bot->error_msg;
						$bot->ReloadConfig();
						$accept++;
						break1;
					}
					else
					if(($lotId > 0) && ($lotId == $obj['id']))
					{
						$N['lotId'] = (int)$lotId;
						$N['senderID'] = (string)$senderID;

						$bot->AcceptFranchiseRequest($N);
						$err = $bot->error_msg;
						$bot->ReloadConfig();
						$accept++;
						break1;
					}
				}
			}
		}

		if(($found > 0) and ($accept == 0))
		{
			$bot->SendMsg('[NEIGHBORS-Franchise] Error: LotSite (' . $lotId . ') is already filled');
		}
		if($found == 0)
		{
			$bot->SendMsg('[NEIGHBORS-Franchise] Error: no empty LotSite were found');
		}
		else
		if($err == "")
		{
			unset($data->flist[$index]);
			$bot->ld->SavePlSettings("neighborsplugin", $data);
		}
	}
	$bot->SendMsg('[NEIGHBORS-Franchise] Accepting done.');
}
//WORK ON NEIGHBORS CITY   =====================================================
$this->AddHook('start_neighbors', 'HelpNeighbors');

function HelpNeighbors($bot)
{
	if($bot->firstrun)
	{
		//not work if it's first bot cycle
		$Name = "neighborsplugin";$Version = "1.07";$Date = "2011-10-11";
		$bot->ld->UpdatePluginVersion($bot, $Name, $Version, $Date);

		//Saving default values to plugin settings in case of nothing found
		$data = $bot->ld->GetPlSettings("neighborsplugin");
		if($data == null)
		{
			$tmp = 'O:8:"stdClass":26:{s:5:"nlist";a:0:{}s:5:"flist";a:0:{}s:3:"all";i:1;s:6:"constr";s:1:"0";s:6:"cropsH";s:1:"0";s:6:"cropsW";s:1:"0";s:6:"cropsR";s:1:"0";s:9:"residence";s:1:"0";s:8:"landmark";s:1:"0";s:9:"municipal";s:1:"0";s:8:"business";s:1:"0";s:5:"trees";s:1:"0";s:6:"Pcycle";s:4:"1000";s:9:"franchise";s:1:"0";s:7:"AcceptN";i:1;s:5:"pause";i:1;s:11:"municipalIN";s:3:"any";s:10:"landmarkIN";s:3:"any";s:11:"residenceIN";s:3:"any";s:10:"businessIN";s:3:"any";s:8:"cropsWIN";s:3:"any";s:8:"cropsHIN";s:3:"any";s:8:"cropsRIN";s:3:"any";s:8:"constrIN";s:3:"any";s:7:"treesIN";s:3:"any";s:11:"franchiseIN";s:9:"ambulance";}';
			$data = unserialize($tmp);
			$bot->ld->SavePlSettings("neighborsplugin", $data);
			unset($data);
		}
		return;
	}
	$msg  = $bot->irc('u').$bot->irc('b');
	$msg .= $bot->irc('cc').'2';
	$msg .= $bot->irc('ff').'13,5'.chr(232).$bot->irc('ff').'14,5';
	$msg .= 'Starting Plugin: NEIGHBORS';
	$bot->SendMsg($msg);

	$data = $bot->ld->GetPlSettings("neighborsplugin");
	//if(($data != null) && !isset($data->pause))
	//{
	//   $data->pause = 1;
	//   $bot->ld->SavePlSettings("neighborsplugin", $data);
	//}
	// accepting neighbors work.
	if(isset($data->AcceptN) && ($data->AcceptN == 1))
	{
		if(is_array($bot->order_visitor_help))
		{
			$bot->SendMsg('=====================================');
			$bot->SendMsg('[NEIGHBORS] Start accepting work from Neighbors...');
			$bot->ReloadConfig();

			foreach($bot->order_visitor_help as $Nuid=>$val)
			{
				$Nuid = $val['senderID'];//senderID
				//$bot->SendMsg('Accepting work from :' . $Nuid);

				if(is_array($val['helpTargets']) && $val['status'] == "unclaimed" && isset($val['senderID']) && count($val['helpTargets']) > 0)
				{
					//status  String
					$bot->redeemVisitorHelpAction($val['helpTargets'], $Nuid);
					// all streakBonus moved to botclass, please look there

					if (($data->sbAccepting==1) && !isset($bot->error_msg))
					{ $bot->streakBonus3(); }
					else
					if(isset($bot->error_msg)) $bot->ReloadConfig();

				}
			}
			$bot->SendMsg('[NEIGHBORS] Accepting work done.');
		}
	}

	//check if it is PAUSED or not
	if(isset($data->pause)) {if($data->pause == 1) return;}

	$data->pause = 0;
	$bot->ld->SavePlSettings("neighborsplugin", $data);

	//if( ! isset($data->nlist)) return;  //not necessary anymore
	//if(count($data->nlist) == 0) return; //not necessary anymore
	if( ! isset($data->Pcycle))
	$data->Pcycle = 1000;
	if($data->Pcycle == 0)
	$data->Pcycle = 1000;
	//if(isset($data->update)) return;
	$now = time();

	$Lotsites = $bot->ld->GetPlSettings("neighborspluginLotsite");
	if( ! is_array($Lotsites))
	{
		// if not exist
		$Lotsites = array();
	}
	else
	{
		// clean older lotsite
		foreach($Lotsites as $key=>$Lotsite)
		{
			$yesterday = $now - 86400;
			if($Lotsite['time'] < $yesterday) {unset($Lotsites[$key]);}
		}
	}

	$bot->SendMsg('=====================================');
	$bot->SendMsg('[NEIGHBORS-Visiting] Starting to visit your neighbors...');
	$bot->ReloadConfig(); //start with the right sequence to prevent OOS erros

	// declare the amounts
	$N = array();
	//var_dump($data); return;

	$item = "constr";//Construction Site
	$N[$item]['className'] = "ConstructionSite";
	$N[$item]['name'] = (string)$data->constrIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->constr;

	$item = "cropsH";// Crops Harvest
	$N[$item]['className'] = "Plot";
	$N[$item]['state'] = "grown";
	$N[$item]['name'] = (string)$data->cropsHIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->cropsH;

	$item = "cropsW";// Crops Water
	$N[$item]['className'] = "Plot";
	$N[$item]['state'] = "planted";
	$N[$item]['name'] = (string)$data->cropsWIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->cropsW;

	$item = "cropsR";// Crops Revive
	$N[$item]['className'] = "Plot";
	$N[$item]['state'] = "withered";
	$N[$item]['name'] = (string)$data->cropsRIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->cropsR;

	$item = "shipsH";// Ships Harvest
	$N[$item]['className'] = "Ship";
	$N[$item]['state'] = "grown";
	$N[$item]['name'] = (string)$data->shipsHIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->shipsH;

	$item = "shipsW";// Ships Water
	$N[$item]['className'] = "Ship";
	$N[$item]['state'] = "planted";
	$N[$item]['name'] = (string)$data->shipsWIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->shipsW;

	$item = "shipsR";// Ships Revive
	$N[$item]['className'] = "Ship";
	$N[$item]['state'] = "withered";
	$N[$item]['name'] = (string)$data->shipsRIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->shipsR;

	//========= Airline =====================================================================
	$arContracts = array(
	"rome_plane" => 1 * 60, //1mins
	"paris_plane" => 5 * 60, //5mins
	"toronto_plane" => 1 * 60 * 60, //1 hours
	"cairo_plane" => 1 * 60 * 60, //1 hours
	"barcelona_plane" => 6 * 60 * 60, //6 hours
	"new_york_plane" => 6 * 60 * 60, //6 hours
	"berlin_plane" => 8 * 60 * 60, //8 hours
	"shanghai_plane" => 12 * 60 * 60, //12 hours
	"rio_plane" => 12 * 60 * 60, //12 hours
	"tokyo_plane" => 18 * 60 * 60, //18 hours
	"mumbai_plane" => 18 * 60 * 60, //18 hours
	"london_plane" => 24 * 60 * 60, //24 hours
	"seoul_plane" => 24 * 60 * 60 //24 hours
	);
	
	$allowWithered = array("barcelona_plane","shanghai_plane","tokyo_plane","london_plane"); //withered contract
	$witheredError = 3; //The amount of extra time the server will give to a crop before it withers
	
	$item = "airH";// Harvest
	$N[$item]['className'] = "Airplane";
	//$N[$item]['itemName'] = "sky_cargo_plane"; 
	//$N[$item]['itemName'] = "cloud_cargo_plane";
	//$N[$item]['itemName'] = "air_cargo_plane";   
	$N[$item]['state'] = "planted";
	$N[$item]['name'] = (string)$data->airHIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->airH;

	$item = "airW";// Accelerate
	$N[$item]['className'] = "Airplane"; 
	$N[$item]['state'] = "planted";
	$N[$item]['name'] = (string)$data->airWIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->airW;

	$item = "airR";// Revive
	$N[$item]['className'] = "Airplane"; 
	$N[$item]['state'] = "planted";
	$N[$item]['name'] = (string)$data->airRIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->airR;

	//============================================================================== 

	$item = "residence";
	$N[$item]['className'] = "Residence";
	$N[$item]['name'] = (string)$data->residenceIN;//   Name of the items to do or ANY
	$N[$item]['cnt_done'] = 0;//   How many did we do
	$N[$item]['cnt_set'] = (int)$data->residence;//   How many can we do (from setting)

	$item = "landmark";
	$N[$item]['className'] = "Landmark";
	$N[$item]['name'] = (string)$data->landmarkIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->landmark;

	$item = "municipal";
	$N[$item]['className'] = "Municipal";
	$N[$item]['name'] = (string)$data->municipalIN;//    $municipal_name = (string) $data->municipalIN;
	$N[$item]['cnt_done'] = 0;//    $municipal_h_cnt = 0;
	$N[$item]['cnt_set'] = (int)$data->municipal;//    $municipal_h_cnt_need = (int) $data->municipal;

	$item = "mall";
	$N[$item]['className'] = "Mall";
	$N[$item]['name'] = (string)$data->mallIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->mall;

	$item = "mall2";
	$N[$item]['className'] = "Mall2";
	$N[$item]['name'] = (string)$data->mall2IN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->mall2;

	$item = "attraction";
	$N[$item]['className'] = "Attraction";
	$N[$item]['name'] = (string)$data->attractionIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->attraction;

	$item = "business";
	$N[$item]['className'] = "Business";
	$N[$item]['name'] = (string)$data->businessIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['cnt_set'] = (int)$data->business;

	$item = "trees";// chop trees
	$N[$item]['className'] = "";//wilderness
	$N[$item]['name'] = (string)$data->treesIN;
	$N[$item]['cnt_done'] = 0;
	$N[$item]['className'] = "";
	$N[$item]['cnt_set'] = (int)$data->trees;

	$visited = 0;
	$waiting = 0;

	$visitlist = array();

	if($data->all)
	{
		$dbnlist = $bot->ld->GetSelect('SELECT * FROM neighborlist order by level');
		foreach($dbnlist as $n)
		{
			//0[uid] NVARCHAR(25) NULL,
			//1[name] NVARCHAR(50) NULL,
			//2[picture] NVARCHAR(50) NULL,
			//3[cityname] NVARCHAR(50) NULL,
			//4[xp] NVARCHAR(10) NULL,
			//5[coins] NVARCHAR(20) NULL,
			//6[level] NVARCHAR(5)  NULL)
			$tmp = $n[0]."|".$n[3].' ('.$n[1].')';
			$tmp = str_replace ( "'", " ", $tmp);
			$visitlist[] = $tmp;
		}
	}
	else
	{
		$visitlist = $data->nlist;
	}

	//var_dump($visilist);
	// Now entering the Neighbor loop... Do this for each neighbor sellected or ALL
	foreach($visitlist as $index=>$sosed)
	{
		// check for maximum visitation per cycle.
		$visited++;
		if($visited > $data->Pcycle) { $waiting++; continue; }

		//if(isset($bot->error_msg))  {$bot->ReloadConfig();}// we got a error

		$tmp = explode("|", $sosed);
		$hostID = trim($tmp[0]);
		$worldName = trim($tmp[1]);

		// msg
		$bot->SendMsg($bot->irc('b').'[NEIGHBORS] Visit:' . $worldName . ' (' . count($visitlist) . ' N to go)');

		//Getting Neighbor informations (world)
		//$amf = new AMFObject($bot->NLoadWorld($hostID, $worldName));
		//$deserializer = new AMFDeserializer($amf->rawData);
		//$deserializer->deserialize($amf);
		//$bod = new MessageBody();
		//$bod = $amf->_bodys[0];
		$amf = $bot->NLoadWorld($hostID, $worldName);
		$bod = $amf->_bodys[0];

		$StillCont = 1;// this to break the loop
		$N['act_done'] = 0;// Actions done for this Neighbor       $act_per_neighbor_cnt = 0;

		//Checking for Errors
		if(isset($bot->error_msg))
		{
			$bot->ReloadConfig();
			$bot->SendMsg('[NEIGHBORS] Exit by Error');
			$StillCont = 0;
		}

		//Still remaining actions
		if($StillCont == 1)
		{
			// check the ammount of energy left for this N.
			$Nenergy = $bod->_value['data'][0]['data']['energyLeft'];//amount of action to be done
			$Nresult = $bod->_value['data'][0]['data']['result'];
			if(isset($bod->_value['data'][0]['data']['reward']['rewards']['xp']))           {$Rxp = $bod->_value['data'][0]['data']['reward']['rewards']['xp'];}
			else           {$Rxp = 0;}
			if(isset($bod->_value['data'][0]['data']['reward']['rewards']['energy']))           {$Renergy = $bod->_value['data'][0]['data']['reward']['rewards']['energy'];}
			else           {$Renergy = 0;}
			if(isset($bod->_value['data'][0]['data']['reward']['rewards']['coins']))           {$Rcoin = $bod->_value['data'][0]['data']['reward']['rewards']['coins'];}
			else           {$Rcoin = 0;}
			if($Rxp == 0)
			{$bot->SendMsg('[NEIGHBORS] You already have visited this neighbor. No rewards');}
			else
			{$bot->SendMsg('[NEIGHBORS] Actions left for this N: ' . $Nenergy . ' Rewarded: XP: ' . $Rxp . ' , Energy: ' . $Renergy . ' Coins : ' . $Rcoin);}
		}

		// Now detect if we already have franchise in this town.
		$franchisHere = array();// empty the array.
		if(is_array($bod->_value['data'][1]['data']['world']['objects']))
		{
			foreach($bod->_value['data'][1]['data']['world']['objects'] as $obj)
			{
				if($obj['className'] == "Business")
				{
					if($obj['itemOwner'] == (string)$bot->zyUid)
					{
						$bot->SendMsg('[NEIGHBORS] You have franchis here. ' . $obj['itemName']);//itemName  String  bus_shoestore
						$franchisHere[$obj['itemName']] = 'Y';
					}
				}

			}// end foreach
		}

		// prep setting to build franchise
		if(!isset($data->franchise)) $data->franchise = 0;
		if(!isset($data->franchiseIN)) $data->franchiseIN = "";
		if((int)$data->franchise > 0 && $data->franchiseIN != "")
		{
			$buildFranchise = "Y";
			$bot->SendMsg('[NEIGHBORS] You are allowed to build franchise here. ');
			if(array_key_exists($data->franchiseIN, $franchisHere))
			{
				$bot->SendMsg('[NEIGHBORS] You already have this franchis here. ' . $data->franchiseIN);
				$buildFranchise = "N";
			}
		}
		else
		{
			$buildFranchise = "N";
			//$bot->SendMsg('N: we are NOT allowed to build franchis here. ' );
		}

		//LotSites  ==============================================================
		if(is_array($bod->_value['data'][1]['data']['world']['objects']))
		{
			foreach($bod->_value['data'][1]['data']['world']['objects'] as $obj)
			{
				// store lotesite in db, so we can show it later.
				if($obj['className'] == "LotSite")
				{
					$Lotsite['time'] = $now;
					$Lotsite['itemName'] = $obj['itemName'];
					$Lotsite['uid'] = $hostID;
					$Lotsite['worldName'] = (string)$worldName;
					$Lotsites[] = $Lotsite;
				}
				// Now check if we can build a franchise here.
				if(($obj['className'] == "LotSite") && ($buildFranchise == "Y") && ($data->franchise > 0))
				{
					$bot->SendMsg('[NEIGHBORS] Found a empty LotSite. Building franchis here NOW. ');
					$object = array();// example
					$object['lotId'] = $obj['id'];//    118
					$object['recipientID'] = $hostID;//    20022222222
					$object['orderResourceName'] = $worldName . substr($data->franchiseIN, 4);//  Jansen's Cinema
					$object['resourceType'] = $data->franchiseIN;//  resourceType  String  bus_movietheater
					//updating franchise name list
					$bot->updateFranchiseName($data->franchiseIN);
					$bot->ReloadConfig();
					//placing franchise
					$bot->placeOrder($object);
					$data->franchise--;
				}

			}// end foreach
		}

		// first look for ConstructionSite
		$items = array("constr", "cropsH", "cropsW", "cropsR", "airH", "airW", "airR", "residence", "landmark", "municipal", "mall", "mall2", "attraction", "business", "trees");
		$NObjects = $bod->_value['data'][1]['data']['world']['objects']; //neighbors items by tonycell
		// for radomized helping option - by pjhkaka
		if (is_array($NObjects)) shuffle($NObjects);

		// <-----------------------------Heart priority - by dada79 ----------------------------------------------------------------------------->
		if ((isset($data->heartP)) && ($data->heartP == 1))
		{
			if(($StillCont == 1 ) && ($N['act_done'] < $Nenergy))
			{
				foreach($NObjects as $obj)
				{
					//check IsConnectedToRoad
					if (in_array($obj['className'],array('ConstructionSite','Residence','Business')))
					{
						if ( ! $obj["isConnectedToRoad"]) continue;
					}

					$obj['VisitorId'] = $hostID;
					if (in_array($obj['className'],array('ConstructionSite','Residence','Business','Plot','Ship','Wilderness')) &&
							(isset($obj['mechanicData']['socialInventory']['heart']) && ($obj['mechanicData']['socialInventory']['heart'] == 1)))
					{
						$bot->BlessNeighbor($obj, $hostID, $data->sbVisiting, "none");
						if(!isset($bot->error_msg))
						{
							switch ($obj['className'])
							{
							case 'ConstructionSite';$item = 'constr';break 1;
							case 'Residence';$item = 'residence';break 1;
							case 'Business';$item = 'business';break 1;
							case 'Wilderness';$item = 'trees';break 1;
							case 'Plot'; switch ($obj['state'])
								{
								case 'grown';$item = 'cropsH';break 2;
								case 'planted';$item = 'cropsW';break 2;
								case 'withered';$item = 'cropsR';break 2;
								}
							case 'Ship'; switch ($obj['state'])
								{
								case 'grown';$item = 'shipsH';break 2;
								case 'planted';$item = 'shipsW';break 2;
								case 'withered';$item = 'shipsR';break 2;
								}	   
							}

							$N[$item]['cnt_done']++;
							$N['act_done']++;
						}
					}
					if(isset($bot->error_msg)) {$bot->ReloadConfig();}
					if($N['act_done'] >= $Nenergy) {$bot->SendMsg('[NEIGHBORS] Max actions done for this neighbor.');$StillCont = 0;break;}
				}
			}
		}
		// <--------------------------------- End Heart priority --------------------------------------------------------------------------->
		//Each Object (item)
		foreach($items as $item)
		{
			if($StillCont == 1 && ($N['act_done'] < $Nenergy) && ($N[$item]['cnt_set'] > 0))
			{
				foreach($NObjects as $obj)
				{
					//check IsConnectedToRoad
					if (in_array($obj['className'],array('ConstructionSite','Residence','Business')))
					{
						if ( ! $obj["isConnectedToRoad"]) continue;
					}

					$obj['VisitorId'] = $hostID;


					
					if(($obj['className'] == $N[$item]['className']) &&
							($N[$item]['cnt_done'] < $N[$item]['cnt_set']) &&
							(strlen($N[$item]['name']) > 0) &&
							($N['act_done'] < $Nenergy))
					{
						

						
						if($N[$item]['className'] == "Plot" || $N[$item]['className'] == "Ship")
						{ if($obj['state'] == $N[$item]['state'])
							{ $stateStatus = "OK"; }
							else
							{ $stateStatus = "NOK"; }
						}
						else
						{ $stateStatus = "OK"; }
	
	
						//Airline
						if($N[$item]['className'] == "Airplane"){
							$Objcontract = $obj["mechanicData"]["contract"];
							if (is_array($Objcontract)){
								
								$contract = $obj["mechanicData"]["contract"]["contractName"];
								$contractStarted = $obj["mechanicData"]["contract"]["plantTime"];
								$timeReady = $contractStarted + $arContracts[$contract];
								$timeWithered = $contractStarted + $witheredError*$arContracts[$contract];	
								
								//Harvest
								if ($item == "airH"){
									// Control for Withered contract only
									if(in_array($contract, $allowWithered)){
										if($obj['state'] == $N[$item]['state'] && $timeReady < time() && $timeWithered > time()){
										    $state = "grown";
											$stateStatus1 = "OK"; 
										}
										else{ 
											$stateStatus1 = "NOK"; 
										}
									}
									else{
										// Control for other contract (can not withered)
										if($obj['state'] == $N[$item]['state'] && $timeReady < time() ){
											$state = "grown";
											$stateStatus1 = "OK"; 
										}
										else{ 
											$stateStatus1 = "NOK"; 
										}
									}
								}
								else
									//Accelerate
									if ($item == "airW"){
										if(($obj['state'] == $N[$item]['state']) && ($timeReady > time())){
											$state = "planted";
											$stateStatus1 = "OK"; 
										}
										else{ 
											$stateStatus1 = "NOK"; 
										}
									}
									else
									//Revive
									//Only on Withered contract
										if (($item == "airR") && (in_array($contract,$allowWithered))){
											if(($obj['state'] == $N[$item]['state']) && ($timeReady < time()) && ($timeWithered < time())){
												$state = "withered";
												$stateStatus1 = "OK"; 
											}
											else{ 
												$stateStatus1 = "NOK"; 
											}
										}
										else{ 
											$stateStatus1 = "NOK"; 
										}								
							}
							else{
								$stateStatus1 = "NOK";
							}								
						}
						else{ 
							$stateStatus1 = "OK"; 
						}
						//$bot->SendMsg($N[$item]['name'].' = '.$stateStatus);
						if($N[$item]['name'] == "any" && $stateStatus == "OK" && $stateStatus1 == "OK")
						{
							//added checking for Attractions/Malls
							if (
									in_array($obj['className'],array('Attraction','Mall','Mall2')) &&
									(!isset($obj['mechanicData']['harvestState']) || ($obj['mechanicData']['harvestState']==""))
									)
							{
								continue;
							}
							
							$bot->BlessNeighbor($obj, $hostID, $data->sbVisiting, $state);
							if(!isset($bot->error_msg)) {$N[$item]['cnt_done']++;$N['act_done']++;}
						}
						else
						{
							//if($N[$item]['name'] == $obj['itemName'] && $stateStatus == "OK")
							if(($N[$item]['name'] == $obj['itemName'] || $N[$item]['name'] == $obj['contractName']) && $stateStatus == "OK" && $stateStatus1 == "OK")
							{
								//added checking for Attractions/Malls
								if (
										in_array($obj['className'],array('Attraction','Mall','Mall2')) &&
										(!isset($obj['mechanicData']['harvestState']) || ($obj['mechanicData']['harvestState']==""))
										)
								{
									continue;
								}
								
								$bot->BlessNeighbor($obj, $hostID, $data->sbVisiting, $state);
								// all streakBonus moved to botclass, please look there
								//$bot->streakBonus3();
								if(!isset($bot->error_msg)) {$N[$item]['cnt_done']++;$N['act_done']++;}
							}
						}
					}
					if(isset($bot->error_msg)) {$bot->ReloadConfig();$bot->SendMsg('[NEIGHBORS] Exit by Error');break;}
					if($N['act_done'] >= $Nenergy) {$bot->SendMsg('[NEIGHBORS] Max actions done for this neighbor.');$StillCont = 0;break;}
				}// end foreach
			}// end if cont
		}// end for each items

		// save lotsite
		if (count($Lotsites)>0) $bot->ld->SavePlSettings("neighborspluginLotsite", $Lotsites);

		// this Neighbors is done reset from list.
		unset($visitlist[$index]);
		$data->nlist = $visitlist;
		$bot->ld->SavePlSettings("neighborsplugin", $data);
	}// end foreach Neighbor

	//Accept pending franchises requests ========================================
	AcceptPendingFRequest($bot, $data);

	// all Neighbors done let's put back to pause.
	if($waiting == 0) $data->pause = 1;
	$bot->ld->SavePlSettings("neighborsplugin", $data);

	// all done, refresh the plugin
	$bot->pm->RefreshMePlugin("Neighbors");

}// end function

//CREATE OR UPDATE NEIGHBORS LIST=========================================================================
$this->AddHook('before_other_work', 'UpdateNList');

function UpdateNList($bot)
{
	$data = $bot->ld->GetPlSettings("neighborsplugin");
	if( ! isset($data->update))
	return;
	if((int)$data->update <> 1)
	return;

	//exit;

	$bot->SendMsg('[Neighbors] Creating neighbors list');

	$res = ($bot->ld->GetSelect('SELECT count(*) as cnt FROM sqlite_master where tbl_name="neighborslist"'));
	if($res[0]["cnt"] > 0)
	{
		$bot->ld->ExecQuery("drop table if exists 'neighborslist'");
	}
	$bot->ld->ExecQuery("CREATE TABLE if not exists [neighborslist]  ([name] NVARCHAR(100)  NULL,[value] VARCHAR(1000)  NULL)  ");

	foreach($bot->cfg->_value['data'][0]['data']['userInfo']['player']['neighbors'] as $neighbor)
	{
		if(isset($bot->error_msg))
		{
			$bot->ReloadConfig();
		}
		$tmp['uid'] = $neighbor;
		$tmp['worldName'] = $neighbor;
		$bot->ld->ExecQuery("insert into neighborslist values ('" . $neighbor . "', '" . serialize($tmp) . "')");
	}
	//
	//    foreach ($bot->neighbors as $neighbor) {
	//        if (isset($bot->error_msg)) {
	//            $bot->ReloadConfig();
	//        }
	//      $amf = new AMFObject(PostInit());

	//      $deserializer = new AMFDeserializer($amf->rawData);
	//      $deserializer->deserialize($amf);
	//      $bod = new MessageBody();
	//      $bod = $amf->_bodys[0];
	//        foreach($bod->_value['data'][0]['data']['inGame'] as $key=>$val){
	//            $inGame[]="1:".$val;
	//        }

	//      foreach($bod->_value['data'][0]['data']['neighbors'] as $fr){
	//            if(in_array($fr['uid'], $inGame)){
	//          unset($tmp);
	//          $tmp['uid'] = $fr['uid'];
	//          $tmp['worldName'] = $fr['cityname'];
	//          $tmp['pic'] = "";
	//          $tmp['level'] = $fr['level'];
	//            $tmp['cash'] = $bod->_value['data'][0]['data']['user']['player']['cash'];
	//          $tmp['gold'] = $fr['gold'];
	//          $tmp['xp'] = $fr['xp'];
	//            $tmp['ncount'] = count($bod->_value['data'][0]['data']['user']['player']['neighbors']);
	//            $tmp['ocount'] = count($bod->_value['data'][0]['data']['user']['world']['objects']);
	//            $tmp['size'] = $bod->_value['data'][0]['data']['user']['world']['sizeX'];
	//            $tmp['lastplayed'] = $bod->_value['data'][0]['data']['user']['player']['lastEnergyCheck'];

	//          $bot->ld->ExecQuery("insert into neighborslist values ('" . $tmp['uid'] . "', '" . serialize($tmp) . "')");
	//            }
	//      }

	//}


	$bot->pm->RefreshMePlugin("Neighbors");

	$data->update = 0;
	$bot->ld->SavePlSettings("neighborsplugin", $data);
}

?>